from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, Currency as c, currency_range, ) import random doc = """ This is a one-shot "Prisoner's Dilemma". Two players are asked separately whether they want to cooperate or defect. Their choices directly determine the payoffs. """ SUPERGROUP_NUM_ERR = 'Wrong number of players per supergroup' class Constants(BaseConstants): name_in_url = 'prisoner' players_per_group = 2 players_per_supergroup = 4 assert players_per_supergroup % players_per_group == 0, \ SUPERGROUP_NUM_ERR num_rounds = 2 instructions_template = 'strategic_draft0/instructions.html' # payoff if 1 player defects and the other cooperates""", betray_payoff = c(300) betrayed_payoff = c(0) # payoff if both players cooperate or both defect both_cooperate_payoff = c(200) both_defect_payoff = c(100) def slice_list(input): ppg = Constants.players_per_group output = [input[i:i+ppg] for i in range(0, len(input), ppg)] for o in output: assert len(o) == ppg, SUPERGROUP_NUM_ERR return output class Subsession(BaseSubsession): def creating_session(self): if self.round_number == 1: assert len(self.get_players()) % \ Constants.players_per_supergroup == 0, \ SUPERGROUP_NUM_ERR for g in self.get_groups(): for p in g.get_players(): p.participant.vars['supergroup'] = int((g.id_in_subsession + 1) // \ (Constants.players_per_supergroup / Constants.players_per_group)) subgroups = set([p.vars['supergroup'] for p in self.session.get_participants()]) new_matrix = [] for s in subgroups: A = [p for p in self.get_players() if p.participant.vars['supergroup'] == s] random.shuffle(A) sliced_supergroup = slice_list(A) new_matrix.extend(sliced_supergroup) print(new_matrix) self.set_group_matrix(new_matrix) #if self.round_number == 1: # assign a random number to participants [1,N] #for p in self.get_players(): #p.participant.vars['id_random'] = random.choice([1,2,3,4,5,6,7,8]) class Group(BaseGroup): def set_payoffs(self): for p in self.get_players(): p.set_payoff() class Player(BasePlayer): decision = models.StringField( choices=[['Cooperate', 'Cooperate'], ['Defect', 'Defect']], doc="""This player's decision""", widget=widgets.RadioSelect, ) supergroup = models.LongStringField() #id_random = models.IntegerField() def other_player(self): return self.get_others_in_group()[0] def set_payoff(self): payoff_matrix = dict( Cooperate=dict( Cooperate=Constants.both_cooperate_payoff, Defect=Constants.betrayed_payoff, ), Defect=dict( Cooperate=Constants.betray_payoff, Defect=Constants.both_defect_payoff ), ) self.payoff = payoff_matrix[self.decision][self.other_player().decision] self.supergroup = str(self.participant.vars['supergroup']) #self.id_random = str(self.participant.vars['id_random'])